package net.butfly.bus.server;

import java.util.HashMap;
import java.util.Map;

import net.butfly.bus.Request;
import net.butfly.bus.Response;
import net.butfly.bus.server.config.ServerConfig;

public final class ServerWrapper {
	private Server server;
	private ServerConfig config;

	public ServerWrapper(Server server, ServerConfig config) {
		super();
		this.server = server;
		this.config = config;
	}

	private static final Map<String, ServerWrapper> servers = new HashMap<String, ServerWrapper>();

	private static void registerSingle(String conf) {
		Server server = new Server(conf);
		register(server, server.getConfig());
	}

	public static void register(String confList) {
		if (confList == null)
			registerSingle(null);
		else
			for (String conf : confList.split(","))
				if (!"".equals(conf.trim()))
					ServerWrapper.registerSingle(conf);
	}

	private static void register(Server server, ServerConfig config) {
		servers.put(server.getServerId(), new ServerWrapper(server, config));
	}

	public static Response execute(Request request) throws Exception {
		return servers.values().iterator().next().server.execute(request);
	}

	public static ServerConfig getConfig(String serverId) {
		return servers.get(serverId).config;
	}

	public static Server get(String serverId) {
		return servers.get(serverId).server;
	}

	public static int size() {
		return servers.size();
	}

}
